//package com.fy.fyspace.mq.consumer;
//
//import cn.hutool.core.lang.UUID;
//import cn.hutool.core.util.StrUtil;
//import com.alibaba.fastjson.JSON;
//import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
//import com.fy.fyspace.common.config.AliYunAiApi;
//import com.fy.fyspace.common.job.xxl.model.XxlJobTaskParam;
//import com.fy.fyspace.common.job.xxl.service.XxlJobService;
//import com.fy.fyspace.common.utils.RedisUtil;
//import com.fy.fyspace.constant.MQConstant;
//import com.fy.fyspace.ex.handler.ExHandler;
//import com.fy.fyspace.mapper.AipictureMapper;
//import com.fy.fyspace.mapper.UploadLogMapper;
//import com.fy.fyspace.model.entity.Aipicture;
//import com.fy.fyspace.model.entity.UploadLog;
//import com.fy.fyspace.model.enums.aipicture.AiPictureTaskStatusEnum;
//import com.fy.fyspace.model.enums.picture.PictureDeleteStatusEnum;
//import com.fy.fyspace.model.mq.ImageOutPaintingMessage;
//import com.fy.fyspace.model.mq.ImageUploadMessage;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.amqp.rabbit.annotation.Exchange;
//import org.springframework.amqp.rabbit.annotation.Queue;
//import org.springframework.amqp.rabbit.annotation.QueueBinding;
//import org.springframework.amqp.rabbit.annotation.RabbitListener;
//import org.springframework.amqp.support.AmqpHeaders;
//import org.springframework.messaging.handler.annotation.Header;
//import org.springframework.messaging.handler.annotation.Payload;
//import org.springframework.stereotype.Component;
//import org.springframework.transaction.annotation.Transactional;
//import com.rabbitmq.client.Channel;
//import cn.hutool.http.HttpRequest;
//import cn.hutool.http.HttpResponse;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.messaging.Message;
//
//import javax.annotation.Resource;
//import java.io.IOException;
//import java.sql.Timestamp;
//import java.util.HashMap;
//import java.util.Map;
//import java.util.Date;
//
///**
// * 图片处理消息消费者
// */
//@Slf4j
//@Component
//public class ImageConsumer {
//
//    @Value("${xxl.job.admin.addresses}")
//    private String adminAddresses;
//
//    @Value("${xxl.job.accessToken}")
//    private String accessToken;
//
//    @Resource
//    private UploadLogMapper uploadLogMapper;
//
//    @Resource
//    private AipictureMapper aipictureMapper;
//
//    @Resource
//    private AliYunAiApi aliYunAiApi;
//
//    @Resource
//    private RedisUtil redisUtil;
//
//    @Resource
//    private XxlJobService xxlJobService;
//
//    private static final long TASK_EXPIRE_TIME = 24 * 60 * 60; // 任务过期时间(秒)
//
//    @RabbitListener(queues = "image.error")
//    @Transactional(rollbackFor = Exception.class)
//    public void handleErrorMessage(@Payload ImageUploadMessage message,
//            @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag,
//            Channel channel) {
//        try {
//            log.info("接收到错误日志消息: {}", message);
//
//            // 保存错误日志
//            UploadLog uploadLog = new UploadLog();
//            uploadLog.setUserId(message.getUserId());
//            uploadLog.setFileName(message.getFileName());
//            uploadLog.setFileSize(message.getFileSize());
//            uploadLog.setErrorMessage(message.getErrorMessage());
//            uploadLog.setCreateTime(new Timestamp(System.currentTimeMillis()));
//            uploadLog.setUpdateTime(new Timestamp(System.currentTimeMillis()));
//
//            uploadLogMapper.insert(uploadLog);
//
//            // 确认消息
//            channel.basicAck(deliveryTag, false);
//        } catch (Exception e) {
//            log.error("处理错误日志消息失败", e);
//            try {
//                // 消息处理失败，拒绝消息并重新入队
//                channel.basicNack(deliveryTag, false, true);
//            } catch (Exception ex) {
//                log.error("拒绝消息失败", ex);
//            }
//        }
//    }
//
//    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = MQConstant.IMAGE_OUTPAINTING_QUEUE), exchange = @Exchange(value = MQConstant.IMAGE_OUTPAINTING_EXCHANGE), key = MQConstant.IMAGE_OUTPAINTING_ROUTING_KEY))
//    @Transactional(rollbackFor = Exception.class)
//    public void handleImageOutPaintingMessage(@Payload ImageOutPaintingMessage imo,
//            Channel channel,
//            @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) throws Exception {
//        try {
//            log.info("收到图片扩展任务消息: {}", imo);
//
//            // 创建AI扩图任务记录
//            Aipicture aipicture = new Aipicture();
//            aipicture.setTaskId(UUID.randomUUID().toString());
//            aipicture.setTaskStatus(AiPictureTaskStatusEnum.PENDING.getCode());
//            aipicture.setCreateTime(new Timestamp(System.currentTimeMillis()));
//            aipicture.setUpdateTime(new Timestamp(System.currentTimeMillis()));
//            aipicture.setUserId(imo.getUserId());
//            aipicture.setPicId(imo.getPicId());
//            aipicture.setSpaceId(imo.getSpaceId());
//
//            // 保存到数据库
//            aipictureMapper.insert(aipicture);
//
//            // 保存到Redis(24小时过期)
//            redisUtil.saveAiTask(aipicture.getTaskId(), aipicture, 24 * 60 * 60);
//
//            try {
//                // 创建XXL-JOB任务
//                Map<String, Object> jobParams = new HashMap<>();
//                jobParams.put("taskId", aipicture.getTaskId());
//
//                XxlJobTaskParam taskParam = new XxlJobTaskParam();
//                taskParam.setJobDesc("AI扩图任务-" + aipicture.getTaskId());
//                taskParam.setExecutorHandler("aiTaskJobHandler");
//                taskParam.setExecutorParam(jobParams);
//                taskParam.setScheduleType("CRON");
//                taskParam.setScheduleConf("*/3 * * * * ?");
//                taskParam.setExecutorRouteStrategy("FIRST");
//                taskParam.setExecutorBlockStrategy("SERIAL_EXECUTION");
//                taskParam.setAuthor("system");
//                taskParam.setAlarmEmail("");
//                taskParam.setTimeout(0);
//                taskParam.setFailRetryCount(0);
//
//                Long jobId = xxlJobService.createAndStartJob(taskParam);
//                aipicture.setJobId(jobId);
//                aipictureMapper.updateById(aipicture);
//
//                // 确认消息
//                channel.basicAck(deliveryTag, false);
//                log.info("mq图片扩展任务消息处理成功: taskId={}", aipicture.getTaskId());
//            } catch (Exception e) {
//                log.error("XXL-JOB任务创建失败，回滚数据: taskId={}, error={}", aipicture.getTaskId(), e.getMessage());
//                // 删除数据库记录
//                aipictureMapper.deleteById(aipicture.getId());
//                // 删除Redis缓存
//                redisUtil.deleteAiTask(aipicture.getTaskId());
//                // 拒绝消息并重新入队
//                channel.basicNack(deliveryTag, false, true);
//                throw e; // 抛出异常触发事务回滚
//            }
//        } catch (Exception e) {
//            log.error("mq处理图片扩展任务消息失败: message={}, error={}", imo, e.getMessage(), e);
//            try {
//                // 消息处理失败，拒绝消息并重新入队
//                channel.basicNack(deliveryTag, false, true);
//            } catch (Exception ex) {
//                log.error("拒绝消息失败: deliveryTag={}, error={}", deliveryTag, ex.getMessage(), ex);
//            }
//            throw e; // 抛出异常触发事务回滚
//        }
//    }
//
//    /**
//     * 停止XXL-JOB任务
//     */
//    private void stopXxlJob(int jobId) {
//        try {
//            // 调用XXL-JOB的Admin API停止任务
//            String url = adminAddresses + "/jobinfo/stop";
//            Map<String, Object> params = new HashMap<>();
//            params.put("id", jobId); // 任务ID
//
//            // 发送HTTP请求停止任务
//            HttpRequest request = HttpRequest.post(url)
//                    .form(params)
//                    .header("XXL-JOB-ACCESS-TOKEN", accessToken);
//
//            HttpResponse response = request.execute();
//
//            if (response.isOk()) {
//                log.info("XXL-JOB任务停止成功: jobId={}", jobId);
//            } else {
//                log.error("XXL-JOB任务停止失败: jobId={}, response={}",
//                        jobId, response.body());
//            }
//        } catch (Exception e) {
//            log.error("XXL-JOB任务停止异常: jobId={}, error={}", jobId, e.getMessage(), e);
//        }
//    }
//}